package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.entity.PmsCategory;
import com.shop.exception.ShopException;
import com.shop.mapper.PmsCategoryMapper;
import com.shop.service.PmsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author lpx610
 * @since 2023-11-03
 */
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory> implements PmsCategoryService {

    @Override
    @Cacheable(value = "pms", key = "'category'")
    public List<PmsCategory> getAll() {
        return this.getByParentId("");
    }

    @Override
    @CacheEvict(value = "pms", key = "'category'")
    public Boolean add(String name, String parentId, Integer level) {
        return this.save(new PmsCategory(name, parentId, level));
    }

    @Override
    @CacheEvict(value = "pms", key = "'category'")
    public Boolean update(String id, String name) {
        return this.updateById(new PmsCategory(id).setName(name));
    }

    @Override
    @CacheEvict(value = "pms", key = "'category'")
    public Boolean delete(String id, Boolean active) {
        //如果是禁用 需要通过id来判断是否存在未禁用的下级
        if (!active && this.getActiveChildrenCount(id) > 0) {
            throw new ShopException("存在未禁用的下级分类，无法禁用当前分类");
        }
        //如果是启用 需要先判断上级是否启用 如果上级未启用 则无法启用当前分类
        if (active && !this.getActiveParentState(id)) {
            throw new ShopException("存在未启用的上级分类，其先启用上级分类");
        }
        return this.updateById(new PmsCategory(id).setActive(active));
    }

    //循环获取每个分类的子集数据
    private List<PmsCategory> getByParentId(String parent_id) {
        QueryWrapper<PmsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parent_id);
        List<PmsCategory> list = this.list(queryWrapper);
        for (PmsCategory pmsCategory : list) {
            List<PmsCategory> children = this.getByParentId(pmsCategory.getId());
            if (children.size() > 0) {
                pmsCategory.setChildren(children);
            }
        }
        return list;
    }

    //获取被启用的下级数量
    private int getActiveChildrenCount(String id) {
        QueryWrapper<PmsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id)
                .eq("active", 1);
        return this.count(queryWrapper);
    }

    //获取父级是否为启用状态
    private Boolean getActiveParentState(String id) {
        String parentId = this.getById(id).getParentId();
        if (StringUtils.isBlank(parentId)) {
            return true;
        }
        return this.getById(parentId).getActive();
    }
}
